package com.example.writting.ui.examples

import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.style.AlignmentSpan
import android.text.style.LeadingMarginSpan
import android.text.style.StyleSpan
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.writting.data.ExampleDataSource
import com.example.writting.databinding.FragmentExamplesBinding
import com.example.writting.model.Example

class ExamplesFragment : Fragment() {

    private var _binding: FragmentExamplesBinding? = null
    private val binding get() = _binding!!

    private val adapter = ExampleAdapter { example ->
        showExampleContent(example)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentExamplesBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupRecyclerView()
        loadExamples()
    }

    private fun setupRecyclerView() {
        binding.examplesRecyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = this@ExamplesFragment.adapter
        }
    }

    private fun loadExamples() {
        // 在显示时对列表进行排序，但不改变原始数据
        val sortedExamples = ExampleDataSource.examples.sortedBy { it.title }
        adapter.updateExamples(sortedExamples)
    }

    private fun showExampleContent(example: Example) {
        binding.examplesRecyclerView.visibility = View.GONE
        binding.contentScrollView.visibility = View.VISIBLE
        binding.backButton.visibility = View.VISIBLE
        
        binding.backButton.setOnClickListener {
            binding.examplesRecyclerView.visibility = View.VISIBLE
            binding.contentScrollView.visibility = View.GONE
            binding.backButton.visibility = View.GONE
            binding.exampleContentTextView.visibility = View.GONE
        }

        binding.exampleContentTextView.apply {
            visibility = View.VISIBLE
            // 构建标题和副标题
            val titleText = buildString {
                append(example.title)
                if (!example.subtitle.isNullOrEmpty()) {
                    append("\n")
                    append(example.subtitle)
                }
            }
            val content = example.content
            val formattedText = SpannableString("$titleText\n\n$content")
            
            // 设置主标题居中
            formattedText.setSpan(
                AlignmentSpan.Standard(android.text.Layout.Alignment.ALIGN_CENTER),
                0,
                example.title.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            
            // 设置副标题居中（如果存在）
            if (!example.subtitle.isNullOrEmpty()) {
                formattedText.setSpan(
                    AlignmentSpan.Standard(android.text.Layout.Alignment.ALIGN_CENTER),
                    example.title.length + 1,
                    example.title.length + 1 + example.subtitle.length,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
            
            // 设置段落缩进
            val paragraphs = content.split("\n")
            var currentPosition = titleText.length + 2 // +2 for the newlines
            paragraphs.forEach { paragraph ->
                if (paragraph.isNotEmpty()) {
                    formattedText.setSpan(
                        LeadingMarginSpan.Standard(60, 0), // 60dp 缩进
                        currentPosition,
                        currentPosition + paragraph.length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                }
                currentPosition += paragraph.length + 1 // +1 for the newline
            }
            
            // 设置加粗文本
            example.boldTexts.forEach { boldText ->
                var startIndex = content.indexOf(boldText)
                if (startIndex != -1) {
                    startIndex += titleText.length + 2 // 调整到正确的位置
                    formattedText.setSpan(
                        StyleSpan(android.graphics.Typeface.BOLD),
                        startIndex,
                        startIndex + boldText.length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                }
            }
            
            text = formattedText
            movementMethod = LinkMovementMethod.getInstance()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 